﻿using BUGCOME.Infrastructure;
using BUGCOME.Model.Auth;
using BUGCOME.Model.Logs;
using SqlSugar.IOC;

namespace BUGCOME.ServiceCore.SqlSugar
{
    
    /// <summary>
    /// 数据权限
    /// </summary>
    public class DataPermi
    {
        /// <summary>
        /// 数据过滤
        /// </summary>
        /// <param name="configId">多库id</param>
        public static void FilterData(int configId)
        {
            //获取当前用户的信息
            var user = JwtUtil.GetLoginUser(App.HttpContext);
            if (user == null) return;

            var db = DbScoped.SugarScope.GetConnectionScope(configId);
            var expUser = Expressionable.Create<UserBase>().And(it => it.DelFlag == 0);
            var expRole = Expressionable.Create<Role>();
            var expLoginlog = Expressionable.Create<UserLoginLog>();
            var expSysMsg = Expressionable.Create<UserMsg>().And(it => it.IsDelete == 0);

            db.QueryFilter.AddTableFilter(expSysMsg.ToExpression());
            //管理员不过滤
            if (user.RoleIds.Any(f => f.Equals(GlobalConstant.AdminRole))) return;


            db.QueryFilter.AddTableFilter(expUser.ToExpression());
            db.QueryFilter.AddTableFilter(expRole.ToExpression());
            db.QueryFilter.AddTableFilter(expLoginlog.ToExpression());
            db.QueryFilter.AddTableFilter<UserOnlineLog>(f => f.UserId == user.UserId, QueryFilterProvider.FilterJoinPosition.Where);
        }
    }
}
